﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Al.UI.Controls
{
    public class CometAsyncHandler: IHttpAsyncHandler
    {
        private CometSession _session;
        private CometOperation _operation;
        private CometController _controller;

        #region IHttpAsyncHandler Members

        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback asyncCallback, object state)
        {
            string sessionID = context.ApplicationInstance.Request.QueryString[0];

            this._session = CometServer.GetSession(sessionID);

            if (this._session == null)
                CometServer.RegisterPage(sessionID);
            this._controller = CometServer.GetCometController(this._session);
            this._operation = new CometOperation(ProcessRequest);

            return this._operation.BeginInvoke(context, asyncCallback, state); 
        }

        public void EndProcessRequest(IAsyncResult result)
        {
            this._operation.EndInvoke(result);
        }

        #endregion

        #region IHttpHandler Members

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            CometServer.WaitForUpdate(this._session);
            context.Response.ContentType = "text/xml";
            if (this._controller.IsDirty)
            {
                this._controller.IsDirty = false;
                context.Response.Write("Dirty");
            }
            else
            {
                context.Response.Write(string.Empty);
            }
        }

        #endregion
    }
}
